<?php
/**
 * Created by PhpStorm.
 * User: LuLingFeng
 * Date: 2017/12/28
 * Time: 13:04
 */

namespace App\Http\Admin\Administration\Models;

use App\Eloquent\Job\Resume\Resume;
use App\Eloquent\Oa\Contacts;
use App\Eloquent\Oa\FlowBusinessTrip;
use App\Eloquent\Oa\FlowBusinessTripTravel;
use App\Eloquent\Oa\FlowCar;
use App\Eloquent\Oa\FlowCarVehicle;
use App\Eloquent\Oa\FlowDaysOff;
use App\Eloquent\Oa\FlowDocument;
use App\Eloquent\Oa\FlowGoOut;
use App\Eloquent\Oa\FlowInterview;
use App\Eloquent\Oa\FlowLeave;
use App\Eloquent\Oa\FlowReimburse;
use App\Eloquent\Oa\FlowReimburseItem;
use App\Eloquent\Oa\FlowResignation;
use App\Eloquent\Oa\FlowSeal;
use App\Eloquent\Oa\FlowSupplement;
use App\Eloquent\Oa\FlowTakingWork;
use App\Eloquent\Oa\FlowCustomerOrder;//新加，客户订单流程
use App\Eloquent\Oa\FlowTransferPost;
use App\Eloquent\Oa\FlowFile;
use App\Eloquent\Ygt\WaitPurchaseMaterial;
use App\Engine\Product;
use App\Repositories\OA\FlowConfigProcessRepository;
use App\Repositories\OA\FlowConfigRepository;
use Faker\Provider\hy_AM\Company;
use Framework\BaseClass\Http\Admin\Model;
use Framework\Services\Push\JPush\JPushService;

use App\Eloquent\Oa\FlowReceiveApplyFor;
use App\Eloquent\Oa\FlowProcurement;
use App\Eloquent\Oa\FlowContract;
use App\Eloquent\Oa\FlowPettyCash;
use App\Eloquent\Oa\FlowSystemSolutions;
use App\Eloquent\Oa\FlowRecruitmentNeeds;
use App\Eloquent\Oa\FlowRewardAndPunish;
use App\Eloquent\Oa\FlowDimission;
use App\Eloquent\Oa\FlowBecomePromoteSalary;
use App\Eloquent\Oa\FlowOvertimeWorkFee;


use App\Engine\Func;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Message;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\Customer;

class Flow extends Model
{
    const RELATE_TYPE_ABBR_FLOW_DOCUMENT = 'doc';
    const RELATE_TYPE_ABBR_FLOW_LEAVE = 'lv';      // 请假
    const RELATE_TYPE_ABBR_FLOW_SEAL_USE = 'su';   // 用章
    const RELATE_TYPE_ABBR_FLOW_CAR_USE = 'cu';    // 用车
    const RELATE_TYPE_ABBR_FLOW_RESIGN = 'rs';     // 离职, 先不用
    const RELATE_TYPE_ABBR_FLOW_TRANSFER_POST = 'tp'; // 岗位调动
    const RELATE_TYPE_ABBR_FLOW_REIMBURSE = 'rb';  // 报销
    const RELATE_TYPE_ABBR_FLOW_EGRESS = 'eg';     // 外出
    const RELATE_TYPE_ABBR_FLOW_BUSINESS_TRIP = 'bt'; // 出差
    const RELATE_TYPE_ABBR_FLOW_HOLIDAY_SHIFT = 'hs'; // 调休
    const RELATE_TYPE_ABBR_FLOW_WORKDAY_SHIT = 'ws';  // 补勤
    const RELATE_TYPE_ABBR_FLOW_OVERTIME_PAY = 'op';     //加班费
    const RELATE_TYPE_ABBR_FLOW_RECEIVE_APPLY_FOR = 'raf';     //领用申请

    const RELATE_TYPE_ABBR_FLOW_PROCUREMENT = 'pro'; //采购申请
    const RELATE_TYPE_ABBR_FLOW_CONTENT = 'con'; // 合同
    const RELATE_TYPE_ABBR_FLOW_PETTY_CASH = 'pc'; // 备用金
    const RELATE_TYPE_ABBR_FLOW_SYSTEM_SOLUTIONS = 'ss'; // 制度方案
    const RELATE_TYPE_ABBR_FLOW_RECEUITMENT_NEEDS = 'rn'; // 招聘需求
    const RELATE_TYPE_ABBR_FLOW_REWARD_AND_PUNISH = 'rap'; // 奖罚申报
    const RELATE_TYPE_ABBR_FLOW_DIMISSION = 'dim'; // 离职
    const RELATE_TYPE_ABBR_FLOW_BECOME_PROMOTE_SALARY = 'bps'; // 转正晋升调薪
    const RELATE_TYPE_ABBR_FLOW_REPLENISH_SIGN = 'res'; // 补签
    const RELATE_TYPE_ABBR_FLOW_INTERVIEW = 'in'; // 面试
    const RELATE_TYPE_ABBR_FLOW_TAKING_WORK = 'tw'; // 入职
    const RELATE_TYPE_ABBR_FLOW_CUSTOMER_ORDER = 'co'; // 客户订单
    const RELATE_TYPE_ABBR_FLOW_PURCHASE_APPLICATION = 'pa'; // 采购申请
    const RELATE_TYPE_ABBR_FLOW_RETURN_PURCHASE_APPLICATION = 'rpa'; // 采购退货

    /**
     * 新建流程
     * @author LuLingFeng
     * @param $type
     * @param $flowData
     * @param $userId
     * @param int $companyId
     * @return null|void
     */
    public function newFlow($type, $flowData, $userId, $companyId = 0)
    {
        $flowConfigProcess = new FlowConfigProcessRepository();

        $data = null;
        if (empty($flowData['serial_number'])) $flowData['serial_number'] = $this->generateSerialNumber($type);

        switch ($type) {
            case self::RELATE_TYPE_ABBR_FLOW_DOCUMENT:
                // 公文流程
                $flowId = 10;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newDocumentFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_LEAVE:
                // 请假流程
                $flowId = 1;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newLeaveFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_SEAL_USE:
                // 用章流程
                $flowId = 2;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newSealUseFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_CAR_USE:
                // 用车流程
                $flowId = 3;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $flowData['branch_data'] = [
                    [
                        'type' => $flowData['type'],
                        'number' => $flowData['number'],
                        'request' => $flowData['request']
                    ]
                ];

                $data = $this->newCarUseFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_RESIGN:
                // 辞职流程
//                $data = $this->newResignFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_TRANSFER_POST:
                // 岗位调动流程
                $flowId = 4;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newTransferPostFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_REIMBURSE:
                // 报销流程
                $flowId = 5;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $flowData['branch_data'] = [
                    [
                        'money' => $flowData['money'],
                        'type' => $flowData['type'],
                        'details' => $flowData['details']
                    ]
                ];

                $data = $this->newReimburseFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_EGRESS:
                // 外出流程
                $flowId = 6;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newEgressFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_BUSINESS_TRIP:
                // 出差流程
                $flowId = 7;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $flowData['branch_data'] = [
                    [
                        'destination' => $flowData['destination'],
                        'start_time' => $flowData['start_time'],
                        'end_time' => $flowData['end_time']
                    ]
                ];

                $data = $this->newBusinessTripFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_HOLIDAY_SHIFT:
                // 调休流程
                $flowId = 8;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newHolidayShiftFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_WORKDAY_SHIT:
                // 补勤流程
                $flowId = 9;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newWorkdayShiftFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_OVERTIME_PAY:
                // 加班费
                $flowId = 11;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newOvertimePayFlow($userId, $companyId, $flowData);

                break;
            case self::RELATE_TYPE_ABBR_FLOW_RECEIVE_APPLY_FOR:
                // 领用申请
                $flowId = 12;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->newReceiveApplyForFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_PROCUREMENT:
                // 采购申请
                $flowId = 13;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->procurementFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_CONTENT:
                // 合同
                $flowId = 14;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->contractFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_PETTY_CASH:
                // 备用金
                $flowId = 15;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->pettyCashFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_SYSTEM_SOLUTIONS:
                // 制度方案
                $flowId = 16;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->systemSolutionsFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_RECEUITMENT_NEEDS:
                // 招聘需求
                $flowId = 17;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->recruitmentNeedsFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_REWARD_AND_PUNISH:
                // 奖罚申报
                $flowId = 18;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->rewardAndPunishFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_DIMISSION:
                // 离职
                $flowId = 19;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->dimissionFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_BECOME_PROMOTE_SALARY:
                // 转正晋升调薪
                $flowId = 20;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->becomePromoteSalaryFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_REPLENISH_SIGN:
                // 补签
                break;
            case self::RELATE_TYPE_ABBR_FLOW_INTERVIEW:
                // 面试
                $flowId = 22;
                $flowData['oa_flow_id'] = $flowId;
                $flowData['oa_flow_config_process_id'] = 0;
                $data = $this->interviewFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_TAKING_WORK:
                // 入职
                $flowId = 23;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->takingWorkFlow($userId, $companyId, $flowData);
                break;
            case self::RELATE_TYPE_ABBR_FLOW_CUSTOMER_ORDER:
                // 客户订单
                $flowId = 25;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id)[0];
                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;
                if(!$flowData['workplace']){
                    xThrow(ERR_PARAMETER, '请选择单位');
                }

                $data = $this->customerOrderFlow($userId, $companyId, $flowData);
                break;

            case self::RELATE_TYPE_ABBR_FLOW_PURCHASE_APPLICATION:
                //采购申请--创建采购申请

                //获取用户信息
                $userId = \App\Engine\Func::getHeaderValueByName('userid');
                $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
                $companyId = $userInfo['company_id'];

                $flowId = 26;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1,
                    'oa_company_id' => $companyId,
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id);
                if(!$endProcess->count()){
                    xSetErrorInfo(1, '未配置完整');
                }
                $endProcess = $endProcess[0];

                //添加新参数
                if (!isset($flowData['material_id']) || empty($flowData['material_id'])) $flowData['material_id'] = '';
                if (!isset($flowData['supplier_id']) || empty($flowData['supplier_id'])) $flowData['supplier_id'] = '';
                if (!isset($flowData['num']) || empty($flowData['num'])) $flowData['num'] = '';
                if (!isset($flowData['content']) || empty($flowData['content'])) $flowData['content'] = '';

                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

                $data = $this->purchaseApplicationFlow($userId, $companyId, $flowData);
                break;

            case self::RELATE_TYPE_ABBR_FLOW_RETURN_PURCHASE_APPLICATION:
                //退货申请

                //获取用户信息
                $userId = \App\Engine\Func::getHeaderValueByName('userid');
                $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
                $companyId = $userInfo['company_id'];

                $flowId = 27;
                $flowConfig = new FlowConfigRepository();
                $flowConfig = $flowConfig->find([
                    'oa_flow_id' => $flowId,
                    'is_use' => 1,
                    'display' => 1,
                    'oa_company_id' => $companyId,
                ]);
                if (!$flowConfig) xThrow(ERR_OA_FLOW_NOT_CONFIGURED);
                $endProcess = $flowConfigProcess->getEndProcess($flowConfig->id);
                if(!$endProcess->count()){
                    xSetErrorInfo(1, '未配置完整');
                }
                $endProcess = $endProcess[0];

                //添加新参数
                if (!isset($flowData['material_id']) || empty($flowData['material_id'])) $flowData['material_id'] = '';
                if (!isset($flowData['supplier_id']) || empty($flowData['supplier_id'])) $flowData['supplier_id'] = '';
                if (!isset($flowData['num']) || empty($flowData['num'])) $flowData['num'] = '';
                if (!isset($flowData['content']) || empty($flowData['content'])) $flowData['content'] = '';

                $flowData['operator_id'] = $endProcess->operator_id;
                $flowData['oa_flow_id'] = $flowConfig->oa_flow_id;
                $flowData['oa_flow_config_process_id'] = $endProcess->id;

//                $data = $this->purchaseApplicationFlow($userId, $companyId, $flowData);
                $data = $this->returnPurchaseApplicationFlow($userId, $companyId, $flowData);
                break;
            default:
                xThrow(ERR_PARAMETER, '不支持的流程类型');
        }
        return $data;
    }

    /**
     * 新建公文
     * @author LuLingFeng
     * @param $userId
     * @param $companyId
     * @param $data
     */
    public function newDocumentFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowDocument([
                'title' => $data['title'],
                'content' => $data['content'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_DOCUMENT,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的公文审批待处理，请及时查看', '公文审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的公文审批抄送，请注意查看', '公文审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    /**
     * 新建请假
     * @author LuLingFeng
     * @param $userId
     * @param $companyId
     * @param $data
     */
    public function newLeaveFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $contacts = Contacts::find($userId);
            if (empty($contacts)) xThrow(ERR_PARAMETER, '无此人员');
            $startTime = is_numeric($data['start_time']) ? $data['start_time'] : strtotime($data['start_time']);
            $endTime = is_numeric($data['end_time']) ? $data['end_time'] : strtotime($data['end_time']);
            $days = ceil(($endTime - $startTime) / 86400);
            $flow = new FlowLeave([
//                'title'          => $data['title'],
//                'scope'          => $data['scope'],
                'type' => $data['type'],
//                'days_scope'     => $data['days_scope'],
                'start_time' => $startTime,
                'end_time' => $endTime,
                'days' => $days,
                'reasons' => $data['reasons'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_LEAVE,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的请假审批待处理，请及时查看', '请假审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的请假审批抄送，请注意查看', '请假审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 离职
    public function newResignFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowResignation([
                'oa_contacts_id' => $userId,
                'oa_company_id' => $companyId,
            ]);
            xAssert($flow->save());
            $workflow = $this->initWorkflow($userId, $flow['id'], $data['serial_number'], Workflow::RELATE_TYPE_FLOW_DOCUMENT, $data['operator_id'], $data['copy_ids']);
            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 岗位调动
    public function newTransferPostFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['adjust_time'] = is_numeric($data['adjust_time']) ? $data['adjust_time'] : strtotime($data['adjust_time']);
            $flow = new FlowTransferPost([
                'new_department' => $data['new_department'],
                'new_position' => $data['new_position'],
                'reasons' => $data['reasons'],
                'adjust_time' => $data['adjust_time'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_TRANSFER_POST,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的岗位调动审批待处理，请及时查看', '岗位调动审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的岗位调动审批抄送，请注意查看', '岗位调动审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
//            if ($t->getMessage() != 'Invalid alias value')
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 用车流程
    public function newCarUseFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['start_time'] = is_numeric($data['start_time']) ? $data['start_time'] : strtotime($data['start_time']);
            $data['return_time'] = is_numeric($data['return_time']) ? $data['return_time'] : strtotime($data['return_time']);
            $flow = new FlowCar([
                'oa_department_id' => $data['oa_department_id'],
                'reasons' => $data['reasons'],
                'start_place' => $data['start_place'],
                'return_place' => $data['return_place'],
                'start_time' => $data['start_time'],
                'return_time' => $data['return_time'],
                'note' => $data['note'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_CAR_USE,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);
            foreach ($data['branch_data'] as $branchData) {
                $branch = new FlowCarVehicle([
                    'oa_flow_car_id' => $flow['id'],
                    'type' => $branchData['type'],
                    'number' => $branchData['number'],
                    'request' => $branchData['request'],
                ]);
                xAssert($branch->save());
                if (!isset($branchData['image_url'])) $branchData['image_url'] = '';
                if (!isset($branchData['enclosure_url'])) $branchData['enclosure_url'] = '';
                $this->saveFile($workflow['id'], $flow['id'], $branch['id'], $branchData['image_url'], $branchData['enclosure_url']);
            }

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的用车审批待处理，请及时查看', '用车审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的用车审批抄送，请注意查看', '用车审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 用章流程
    public function newSealUseFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowSeal([
                'oa_department_id' => $data['oa_department_id'],
                'operator' => $data['operator'],
                'file_name' => $data['file_name'],
                'file_number' => $data['file_number'],
                'file_type' => $data['file_type'],
                'seal_type' => $data['seal_type'],
                'note' => $data['note'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_SEAL_USE,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的用章审批待处理，请及时查看', '用章审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的用章审批抄送，请注意查看', '用章审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 报销流程
    public function newReimburseFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowReimburse();
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_REIMBURSE,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);
            foreach ($data['branch_data'] as $branchData) {
                $branch = new FlowReimburseItem([
                    'oa_flow_reimburse_id' => $flow['id'],
                    'money' => $branchData['money'],
                    'type' => $branchData['type'],
                    'details' => $branchData['details'],
                ]);
                xAssert($branch->save());
                if (!isset($branchData['image_url'])) $branchData['image_url'] = '';
                if (!isset($branchData['enclosure_url'])) $branchData['enclosure_url'] = '';
                $this->saveFile($workflow['id'], $flow['id'], $branch['id'], $branchData['image_url'], $branchData['enclosure_url']);
            }

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的报销审批待处理，请及时查看', '报销审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的报销审批抄送，请注意查看', '报销审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 外出流程
    public function newEgressFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['start_time'] = is_numeric($data['start_time']) ? $data['start_time'] : strtotime($data['start_time']);
            $data['end_time'] = is_numeric($data['end_time']) ? $data['end_time'] : strtotime($data['end_time']);
            $data['duration'] = ceil(($data['end_time'] - $data['start_time']) / 3600);
            $flow = new FlowGoOut([
                'start_time' => $data['start_time'],
                'end_time' => $data['end_time'],
                'duration' => $data['duration'],
                'reasons' => $data['reasons'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_EGRESS,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的外出审批待处理，请及时查看', '外出审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的外出审批抄送，请注意查看', '外出审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 出差流程
    public function newBusinessTripFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowBusinessTrip([
                'reasons' => $data['reasons'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_BUSINESS_TRIP,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);
            foreach ($data['branch_data'] as $branchData) {
                $branchData['start_time'] = is_numeric($branchData['start_time']) ? $branchData['start_time'] : strtotime($branchData['start_time']);
                $branchData['end_time'] = is_numeric($branchData['end_time']) ? $branchData['end_time'] : strtotime($branchData['end_time']);
                $branchData['duration'] = ceil(($branchData['end_time'] - $branchData['start_time']) / 86400);
                $branch = new FlowBusinessTripTravel([
                    'oa_flow_business_trip_id' => $flow['id'],
                    'destination' => $branchData['destination'],
                    'start_time' => $branchData['start_time'],
                    'end_time' => $branchData['end_time'],
                    'duration' => $branchData['duration'],
                ]);
                xAssert($branch->save());
                if (!isset($branchData['image_url'])) $branchData['image_url'] = '';
                if (!isset($branchData['enclosure_url'])) $branchData['enclosure_url'] = '';
                $this->saveFile($workflow['id'], $flow['id'], $branch['id'], $branchData['image_url'], $branchData['enclosure_url']);
            }

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的出差审批待处理，请及时查看', '出差审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的出差审批抄送，请注意查看', '出差审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 调休流程
    public function newHolidayShiftFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['start_time'] = is_numeric($data['start_time']) ? $data['start_time'] : strtotime($data['start_time']);
            $data['end_time'] = is_numeric($data['end_time']) ? $data['end_time'] : strtotime($data['end_time']);
            $data['duration'] = ceil(($data['end_time'] - $data['start_time']) / 3600);
            $flow = new FlowDaysOff([
                'start_time' => $data['start_time'],
                'end_time' => $data['end_time'],
                'duration' => $data['duration'],
                'reasons' => $data['reasons'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_HOLIDAY_SHIFT,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的调休审批待处理，请及时查看', '调休审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的调休审批抄送，请注意查看', '调休审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }


    // 加班费流程
    public function newOvertimePayFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['start_time'] = is_numeric($data['start_time']) ? $data['start_time'] : strtotime($data['start_time']);
            $data['end_time'] = is_numeric($data['end_time']) ? $data['end_time'] : strtotime($data['end_time']);
            $data['duration'] = ceil(($data['end_time'] - $data['start_time']) / 3600);
            $flow = new FlowOvertimeWorkFee([
                'start_time' => $data['start_time'],
                'end_time' => $data['end_time'],
                'duration' => $data['duration'],
                'workplace' => $data['workplace'],
                'work_content' => $data['work_content'],
                'overtime_pay' => $data['overtime_pay'],
                'table_money' => $data['table_money'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_OVERTIME_PAY,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的加班费审批待处理，请及时查看', '加班费审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的加班费审批抄送，请注意查看', '加班费审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 领用申请
    public function newReceiveApplyForFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['date'] = is_numeric($data['date']) ? $data['date'] : strtotime($data['date']);

            $flow = new FlowReceiveApplyFor([
                'date' => $data['date'],
                'name' => $data['name'],
                'specification' => $data['specification'],
                'number' => $data['number'],
                'use' => $data['use'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_RECEIVE_APPLY_FOR,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的领用申请审批待处理，请及时查看', '领用申请审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的领用申请审批抄送，请注意查看', '领用申请',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 采购申请
    public function procurementFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['deadline'] = is_numeric($data['deadline']) ? $data['deadline'] : strtotime($data['deadline']);

            $flow = new FlowProcurement([
                'name' => $data['name'],
                'format' => $data['format'],
                'number' => $data['number'],
                'prise' => $data['prise'],
                'total' => $data['total'],
                'purpose' => $data['purpose'],
                'supplier' => $data['supplier'],
                'deadline' => $data['deadline'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_PROCUREMENT,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的采购申请审批待处理，请及时查看', '采购申请审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的采购申请审批抄送，请注意查看', '采购申请',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 合同
    public function contractFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowContract([
                'name' => $data['name'],
                'purpose' => $data['purpose'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_CONTENT,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的合同审批待处理，请及时查看', '合同审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的合同审批抄送，请注意查看', '合同审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 备用金
    public function pettyCashFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['apply_date'] = is_numeric($data['apply_date']) ? $data['apply_date'] : strtotime($data['apply_date']);
            $flow = new FlowPettyCash([
                'apply_date' => $data['apply_date'],
                'money' => $data['money'],
                'purpose' => $data['purpose'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_PETTY_CASH,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的备用金审批待处理，请及时查看', '备用金审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的备用金审批抄送，请注意查看', '备用金审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

//制度方案
    public function systemSolutionsFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['do_time'] = is_numeric($data['do_time']) ? $data['do_time'] : strtotime($data['do_time']);
            $flow = new FlowSystemSolutions([
                'name' => $data['name'],
                'content' => $data['content'],
                'do_time' => $data['do_time'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_SYSTEM_SOLUTIONS,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的制度方案审批待处理，请及时查看', '制度方案审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的制度方案审批抄送，请注意查看', '制度方案审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 招聘需求
    public function recruitmentNeedsFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['requirement_time'] = is_numeric($data['requirement_time']) ? $data['requirement_time'] : strtotime($data['requirement_time']);
            $flow = new FlowRecruitmentNeeds([
                'name' => $data['name'],
                'person_number' => $data['person_number'],
                'deparment' => $data['deparment'],
                'requirement' => $data['requirement'],
                'requirement_time' => $data['requirement_time'],

            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_RECEUITMENT_NEEDS,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的招聘需求审批待处理，请及时查看', '招聘需求审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的招聘需求审批抄送，请注意查看', '招聘需求审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 奖罚申报
    public function rewardAndPunishFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['time'] = is_numeric($data['time']) ? $data['time'] : strtotime($data['time']);
            $flow = new FlowRewardAndPunish([
                'oa_contact_id' => $data['oa_contact_id'],
                'type' => $data['type'],
                'reason' => $data['reason'],
                'time' => $data['time'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_REWARD_AND_PUNISH,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的奖罚申报审批待处理，请及时查看', '奖罚申报审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的奖罚申报审批抄送，请注意查看', '奖罚申报审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 离职
    public function dimissionFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['time'] = is_numeric($data['time']) ? $data['time'] : strtotime($data['time']);
            $flow = new FlowDimission([
                'oa_contact_id' => $data['oa_contact_id'],
                'reason' => $data['reason'],
                'time' => $data['time'],
            ]);
            xAssert($flow->save());
            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_DIMISSION,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的离职审批待处理，请及时查看', '离职审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的离职审批抄送，请注意查看', '离职审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 转正，晋升，调薪
    public function becomePromoteSalaryFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowBecomePromoteSalary([
                'type' => $data['type'],
                'oa_contact_id' => $data['oa_contact_id'],
                'reason' => $data['reason'],
                'current_salary' => $data['current_salary'],
                'adjustment_salary' => $data['adjustment_salary'],
                'note' => $data['note'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_BECOME_PROMOTE_SALARY,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的转正，晋升，调薪审批待处理，请及时查看', '转正，晋升，调薪审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的转正，晋升，调薪审批抄送，请注意查看', '转正，晋升，调薪审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 面试
    public function interviewFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $flow = new FlowInterview([
                'job_resume_id' => $data['resume_id'],
                'job_recruitment_id' => $data['recruitment_id'],
                'note' => $data['note'] ?: '',
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_INTERVIEW,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的面试审批待处理，请及时查看', '面试审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的面试审批抄送，请注意查看', '面试审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 入职流程
    public function takingWorkFlow($userId, $companyId, $data)
    {
        // 通过通讯录ID获取用户ID
        $contacts = Contacts::find($userId, ['id', 'user_id']);
        // 通过用户ID，获取该用户的简历ID
        $resumeInfo = Resume::where('user_id', $contacts->user_id)->first(['id']);
        if (!$resumeInfo) xThrow(ERR_JOB_RESUME_NOT_EXIST);

        try {
            \DB::beginTransaction();
            $flow = new FlowTakingWork([
                'job_resume_id' => $resumeInfo->id,
                'note' => $data['note'] ?: '',
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_TAKING_WORK,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的入职审批待处理，请及时查看', '入职审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的入职审批抄送，请注意查看', '入职审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 客户订单
    public function customerOrderFlow($userId, $companyId, $data)
    {
        try {
            //获取用户信息
            $userId = Func::getHeaderValueByName('userid');
            $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
            $companyId = $userInfo['company_id'];

            //获取用户id对应的客户id
            $customerId = Customer::where(['user_id' => $userId])->first();
            if($customerId){
                $customerId = $customerId->id;
            }else{
                $customerId = 0;
            }



            \DB::beginTransaction();
            $flow = new FlowCustomerOrder([
                'workplace' => $data['workplace'],
                'uid' => $userId,
                'company_id' => $companyId,
                'customer_id' => $customerId,
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,
                'creator_id' => $userId,
                'related_id' => $flow['id'],
                'serial_number' => $data['serial_number'],
                'related_type' => Workflow::RELATE_TYPE_FLOW_TAKING_WORK,
                'dispose_code' => 1000,
                'step' => 1,
                'assignee_id' => $data['operator_id'],
                'oa_flow_id' => $data['oa_flow_id'],
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
            ];

            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            //获取下单人权限列表
            $appnodeId = 1;//有下单功能
            $privilegeList = Privilege::getPrivilegeIds($companyId, $appnodeId);

            foreach ($privilegeList as $privilegeId){
                //发送消息给下单人
                $data           = [
                    'company_id'=>$companyId, 'privilege_id'=>$privilegeId,
                    'form_user_id'=>$userId, 'to_user_id'=>'',
                    'foreign_key'=>0,
                    'type'=>16,'type_id'=>$flow->id,
                    'title'=>'客户订单','content'=>'有新的订单'
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }

        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    // 采购申请
    public function purchaseApplicationFlow($userId, $companyId, $data)
    {
        try {
            //获取用户信息
            $userId = \App\Engine\Func::getHeaderValueByName('userid');
            $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
            $companyId = $userInfo['company_id'];

            \DB::beginTransaction();

            ////将材料按供应商划分
            $materialSupplierList = [];
            $noPurchaseMaterialIdList = [];

            //兼容异常
            $data['order_id'] = isset($data['order_id']) ? $data['order_id'] : '';

            //2019-01-24 Linwei 记录已选材料
            $choosedMaterialIdArr = [];
            //先判断数据是否有异常
            if(isset($data['material_list']) && $data['material_list']) {
                $allMaterialList = \GuzzleHttp\json_decode(htmlspecialchars_decode($data['material_list']), true);
                if (!empty($allMaterialList)) {
                    foreach ($allMaterialList as $supplierMaterilRow){
                        $supplierId = $supplierMaterilRow['supplier_id'];
                        $materialList = $supplierMaterilRow['material_list'];
                        if(!is_array($materialList)){
                            $materialList = \GuzzleHttp\json_decode(htmlspecialchars_decode($supplierMaterilRow['material_list']), true);
                        }

                        //未采购的材料
                        if($supplierId == -1){
                            $noPurchaseMaterialIdList = $materialList;
                            //创建新的待采购单

                            continue;
                        }

                        //限制采购数量为0&&采购单价为0
                        if(!empty($materialList)){
                            foreach ($materialList as $materialRow) {
                                if (empty($materialRow)) {
                                    continue;
                                }

                                $tmpMaterialId = $materialRow['material_id'];
                                $tmpMaterialNum = isset($materialRow['num']) ? $materialRow['num'] : 0;
                                $tmpMaterialPrice = $materialRow['price'];


                                //限制采购数量为0&&采购单价为0
                                if($tmpMaterialNum == 0){
                                    $re = [
                                        'code' => 1,
                                        'message' => '请填写采购数量',
                                    ];
                                    echo \GuzzleHttp\json_encode($re);die();
                                }
                                if($tmpMaterialPrice == 0){
                                    $re = [
                                        'code' => 1,
                                        'message' => '请填写采购单价',
                                    ];
                                    echo \GuzzleHttp\json_encode($re);die();
                                }
                            }
                        }
                    }
                }
            }



            $alreadyPurchaseMaterialIdsArr = [];

            if(isset($data['material_list']) && $data['material_list']){
                $allMaterialList = \GuzzleHttp\json_decode(htmlspecialchars_decode($data['material_list']), true);
                if(!empty($allMaterialList)){

                    foreach ($allMaterialList as $supplierMaterilRow){
                        $supplierId = $supplierMaterilRow['supplier_id'];
                        $finishedDate = isset($supplierMaterilRow['finished_date']) ? $supplierMaterilRow['finished_date'] : '';
                        $remark = isset($supplierMaterilRow['remark']) ? $supplierMaterilRow['remark'] : '';

                        $materialList = $supplierMaterilRow['material_list'];
                        if(!is_array($materialList)){
                            $materialList = \GuzzleHttp\json_decode(htmlspecialchars_decode($supplierMaterilRow['material_list']), true);
                        }

                        //未采购的材料
                        if($supplierId == -1){
                            $noPurchaseMaterialIdList = $materialList;
                            //创建新的待采购单

                            continue;
                        }

                        //支付方式
                        $payMethod = '';
                        $tmpObj = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$supplierId])->first();
                        if($tmpObj){
                            $payMethod = $tmpObj['pay_type'];
                        }

                        ////生成采购编号
                        //获取是当天的第几单
                        $dayStartTime = strtotime(date('Ymd'));
                        $intradayOrderCount = \App\Eloquent\Ygt\Purchase::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();

                        $ordeTitleIndex = '';
                        $intradayOrderCount++;
                        if ($intradayOrderCount < 10) {
                            $ordeTitleIndex = sprintf('0%d', $intradayOrderCount);
                        } else {
                            $ordeTitleIndex = $intradayOrderCount;
                        }
                        $purchaseNumber = 'CG' . date('ymd') . $ordeTitleIndex;


                        $flow = new \App\Eloquent\Ygt\Purchase([
                            'uid' => $userId,
                            'company_id' => $companyId,
                            'purchase_number' => $purchaseNumber,
                            'payment_method' => $payMethod,//支付方式
                            'finished_date' => $finishedDate,//交货日期
//                            'application_cause' => isset($data['application_cause']) ? $data['application_cause'] : '',//申请事由
                            'application_cause' =>  '',//申请事由
                            'supplier_id' => $supplierId,
                            'content' => $remark,
                            'order_id' => isset($data['order_id']) ? $data['order_id'] : '',
                            'status' => 1,//状态，默认1-待审核
                        ]);
                        xAssert($flow->save());



                        //存入采购申请材料表
                        $allMoney = 0;//采购总金额

                        //组织信息 材料列表
                        $msgML = 'rnrn材料列表';
                        $msgML .= 'rnrn[名称][数量][单价]';
                        if(!empty($materialList)){
                            foreach ($materialList as $materialRow){
                                if(empty($materialRow)){
                                    continue;
                                }

                                $tmpMaterialId = $materialRow['material_id'];
                                //2019-01-24 Linwei
                                $choosedMaterialIdArr[] = $tmpMaterialId;
                                if (isset($materialRow['assemblage_material_id']))
                                    $choosedMaterialIdArr[] = 'A'.$materialRow['assemblage_material_id'];

                                $tmpMaterialNum = $materialRow['num'];
                                $tmpMaterialPrice = $materialRow['price'];

                                $allMoney += $tmpMaterialNum*$tmpMaterialPrice;

                                $purchaseMaterialObj = \App\Eloquent\Ygt\PurchaseMaterial::firstOrNew(['id'=>'']);
                                $purchaseMaterialRow = [
                                    'purchase_id' => $flow['id'],
                                    'material_id' => $tmpMaterialId,
                                    'num' => $tmpMaterialNum,
                                    'price' => $tmpMaterialPrice,
                                    'company_id' => $companyId,
                                ];

                                $alreadyPurchaseMaterialIdsArr[] = $tmpMaterialId;

                                $purchaseMaterialObj->fill($purchaseMaterialRow);
                                $purchaseMaterialObj->save();

                                //获取材料名称
                                $product_info = \App\Engine\Product::getProductInfo($tmpMaterialId);
                                $prdocut_name = $product_info['product_name'];

                                $msgML.="rnrn[$prdocut_name][$tmpMaterialNum][$tmpMaterialPrice]";
                            }
                        }


                        $workflowSaveData = [
                            'oa_company_id' => $companyId,
                            'creator_id' => $userId,
                            'related_id' => $flow['id'],
                            'serial_number' => $data['serial_number'],
                            'related_type' => Workflow::RELATE_TYPE_FLOW_PURCHASE_APPLICATION,
                            'dispose_code' => 1000,
                            'step' => 1,
                            'assignee_id' => $data['operator_id'],
                            'oa_flow_id' => $data['oa_flow_id'],
                            'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
                        ];

                        $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

                        $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

                        $workFlowId = $data['oa_flow_id'];

                        ////发送消息
                        //发送消息给下一步审批人
                        $messageData           = [
                            'company_id'=> $companyId,
                            'privilege_id'=> '',
                            'form_user_id'=> $userId,
                            'to_user_id'=> $data['operator_id'],
                            'foreign_key'=> $workflow['id'],
                            'type'=>18,
                            'type_id'=>$workflow['id'],
                            'title'=>'采购申请',
                            'content'=>'有新的申请',
                            'theme'=>'采购申请'
                        ];
                        \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);

                        ////发送消息
                        //给供应商发送消息
                        $arr                = [
                            'pay_method'  => $payMethod,
                            'supplier_name' => $tmpObj['title'],
                            'purchase_number'=>$flow['purchase_number'],
                            'finished_date'=> $finishedDate,
                            'money'=>$allMoney,
                            'work_flow_id'=>$workflow['id'],
                            'seller_company_id'=>$flow['supplier_id'],
                            'user_id'=>$flow['uid'],
                            'company_id'=>$flow['company_id'],
                            'purchase_id'=>$flow['id'],
                        ];

                        $companyId          = $arr['company_id'];
                        $userId             = $arr['user_id'];
                        $foreignKey         = $arr['work_flow_id'];
                        $typeId             = $arr['purchase_id'];
                        //26=>'采购订单',//'工厂采购员发起采购时给供应商发消息',
                        $where                  = ['company_id'=>$companyId,'id'=>$arr['seller_company_id']];
                        $sellerCompany          = \App\Eloquent\Ygt\SellerCompany::getInfo($where);
                        if($sellerCompany)
                        {
                            $companyName =    \App\Eloquent\Ygt\Company::getOneValueById($companyId,'title');

                            $sellerUserId       = $sellerCompany->user_id;
                            $messageContent     = '工厂名称：'.$companyName;
                            $messageContent     .= 'rnrn采购单号: '.$arr['purchase_number'];
                            $messageContent     .= 'rnrn采购金额: '.$arr['money'];
                            $messageContent     .= 'rnrn交货日期: '.$arr['finished_date'];
                            $messageContent     .= $msgML;
                            $sellerArr          = config('ygt.seller_arr');
                            $messageCompanyId   = $sellerArr['company_id'];
                            $messageData        = [
                                'company_id' => $messageCompanyId,
                                'privilege_id' => 0,
                                'form_user_id' => $userId,
                                'to_user_id' => $sellerUserId,
                                'foreign_key' => $foreignKey,
                                'type' => 26,
                                'type_id' => $typeId,
                                'title' => '采购订单',
                                'content' => $messageContent,
                                'type_status' => 1,
                                'theme'=>'采购询单'
                            ];
                            \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);
                        }
                        //27=>'工单采购',//工厂采购员发起采购时给仓库发消息
                        $privilegeIdArr     = \App\Eloquent\Ygt\Privilege::getPrivilegeIds( $companyId, 3 );
                        foreach($privilegeIdArr as $key=>$val)
                        {
                            $messageContent     = '供应商：'.$arr['supplier_name'];
                            $messageContent     .= 'rnrn采购单号: '.$arr['purchase_number'];
                            $messageContent     .= 'rnrn交货日期: '.$arr['finished_date'];
                            $messageContent     .= $msgML;
                            $messageData        = [
                                'company_id' => $companyId,
                                'privilege_id' => $val,
                                'form_user_id' => $userId,
                                'to_user_id' => 0,
                                'foreign_key' => $foreignKey,
                                'type' => 27,
                                'type_id' => $typeId,
                                'title' => '工单采购',
                                'content' => $messageContent,
                                'type_status' => 1,
                                'theme'=>'用料采购'
                            ];
                            \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);
                        }
                        //28=>'工单采购',//工厂采购员发起采购时给财务发消息
                        $privilegeIdArr     = \App\Eloquent\Ygt\Privilege::getPrivilegeIds( $companyId, 11 );
                        foreach($privilegeIdArr as $key=>$val)
                        {
                            $messageContent     = '供应商：'.$arr['supplier_name'];
                            $messageContent     .= 'rnrn采购单号: '.$arr['purchase_number'];
                            $messageContent     .= 'rnrn交货日期: '.$arr['finished_date'];
                            $messageContent     .= 'rnrn结算方式: '.$arr['pay_method'];
                            $messageContent     .= 'rnrn采购总金额: '.$arr['money'];
                            $messageData        = [
                                'company_id' => $companyId,
                                'privilege_id' => $val,
                                'form_user_id' => $userId,
                                'to_user_id' => 0,
                                'foreign_key' => $foreignKey,
                                'type' => 28,
                                'type_id' => $typeId,
                                'title' => '工单采购',
                                'content' => $messageContent,
                                'type_status' => 1,
                                'theme'=>'用料采购预付款'
                            ];
                            \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);
                        }

                    }

                    //2019-01-24 获取待采购单里的未选材料,这个修改只处理了存在wait_purchase_id的情况，没有wait_purchase_id的情况没有处理
                    $waitMaterialIdList = [];
                    if(isset($data['wait_purchase_id']) && $data['wait_purchase_id']) {
                        $waitMaterialIdList = \App\Eloquent\Ygt\WaitPurchaseMaterial::where(['wait_purchase_id' => $data['wait_purchase_id']])
                            ->whereNotIn('material_id', $choosedMaterialIdArr)->get(['material_id'])->toArray();
                    }
                    if(isset($data['wait_purchase_id']) && $data['wait_purchase_id']){
                        $waitPurchaseObj = \App\Eloquent\Ygt\WaitPurchase::where(['id'=>$data['wait_purchase_id']])->first();
                        if($waitPurchaseObj){
                            //重新组织还未采购的材料信息
                            //2019-01-24 Linwei
//                            if(!empty($waitMaterialIdList)){
//                            //if($supplierId != -1){//不知这个特殊处理的原因，先这样写
//                                //获得未采购的记录id
//                                $noPurchaseMaterialIdList = WaitPurchaseMaterial::where('wait_purchase_id','=',$waitPurchaseObj->id)
//                                    ->whereNotIn('material_id',$alreadyPurchaseMaterialIdsArr)
//                                    ->get(['material_id'])->toArray();
//                            }
                            //将老的待采购单更新为已处理
                            $waitPurchaseObj->status = 2;
                            $waitPurchaseObj->save();


                            //如有未采购的材料，新生成待采购单
                            //2019-01-24 Linwei
                            $noPurchaseMaterialIdList = $waitMaterialIdList;
                            if(!empty($waitMaterialIdList)){
                            //if(!empty($noPurchaseMaterialIdList)) {
                                $tmpObj = \App\Eloquent\Ygt\WaitPurchase::firstOrNew(['id'=>'']);
                                $tmpInsertRow = [
                                    'order_id' => $waitPurchaseObj['order_id'],
                                    'type' => 2,
                                    'status' => 1,
                                    'uid' => $userId,
                                    'company_id' => $companyId,
                                ];
                                $tmpObj->fill($tmpInsertRow);
                                $tmpObj->save();
                                $tmpWaitPurchaseId = $tmpObj->id;

                                foreach ($noPurchaseMaterialIdList as $noPurchaseMaterialIdRow) {
                                    $tmpMaterialId = $noPurchaseMaterialIdRow['material_id'];

                                    $tmpObj = \App\Eloquent\Ygt\WaitPurchaseMaterial::firstOrNew(['id'=>'']);
                                    $tmpInsertRow = [
                                        'wait_purchase_id' => $tmpWaitPurchaseId,
                                        'material_id' => $tmpMaterialId,
                                    ];
                                    $tmpObj->fill($tmpInsertRow);
                                    $tmpObj->save();
                                }
                            }
                        }

                    }else{
                        //兼容
                        $waitPurchaseObj = \App\Eloquent\Ygt\WaitPurchase::where(['order_id'=>$data['order_id'],'type'=>1,'status'=>1])->first();
                        if($waitPurchaseObj){
                            //重新组织还未采购的材料信息
                            if($supplierId != -1){//不知这个特殊处理的原因，先这样写
                                //获得未采购的记录id
                                $noPurchaseMaterialIdList = WaitPurchaseMaterial::where('wait_purchase_id','=',$waitPurchaseObj->id)
                                    ->whereNotIn('material_id',$alreadyPurchaseMaterialIdsArr)
                                    ->get(['material_id'])->toArray();
                            }

                            $waitPurchaseObj->status = 2;
                            $waitPurchaseObj->save();

                            //如有未采购的材料，新生成待采购单
                            if(!empty($noPurchaseMaterialIdList)) {
                                $tmpObj = \App\Eloquent\Ygt\WaitPurchase::firstOrNew(['id'=>'']);
                                $tmpInsertRow = [
                                    'order_id' => $waitPurchaseObj['order_id'],
                                    'type' => 2,
                                    'status' => 1,
                                    'uid' => $userId,
                                    'company_id' => $companyId,
                                ];
                                $tmpObj->fill($tmpInsertRow);
                                $tmpObj->save();
                                $tmpWaitPurchaseId = $tmpObj->id;

                                foreach ($noPurchaseMaterialIdList as $noPurchaseMaterialIdRow) {
                                    $tmpMaterialId = $noPurchaseMaterialIdRow['material_id'];

                                    $tmpObj = \App\Eloquent\Ygt\WaitPurchaseMaterial::firstOrNew(['id'=>'']);
                                    $tmpInsertRow = [
                                        'wait_purchase_id' => $tmpWaitPurchaseId,
                                        'material_id' => $tmpMaterialId,
                                    ];
                                    $tmpObj->fill($tmpInsertRow);
                                    $tmpObj->save();
                                }
                            }
                        }
                    }






                }else{
                    $re = [
                        'code' => 1,
                        'message' => '请选择需要采购的材料',
                    ];

                    echo \GuzzleHttp\json_encode($re);die();

                }
            }else{
                $re = [
                    'code' => 1,
                    'message' => '请选择需要采购的材料',
                ];

                echo \GuzzleHttp\json_encode($re);die();
            }


        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }

        \DB::commit();
    }

    // 退货申请
    public function returnPurchaseApplicationFlow($userId, $companyId, $data)
    {
        try {
            //获取用户信息
            $userId = \App\Engine\Func::getHeaderValueByName('userid');
            $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
            $companyId = $userInfo['company_id'];


            \DB::beginTransaction();
            ////将材料按供应商划分
            $materialSupplierList = [];
            if(isset($data['material_list']) && $data['material_list']){
                $materialList = \GuzzleHttp\json_decode(htmlspecialchars_decode($data['material_list']), true);
                if(!empty($materialList)){
                    foreach ($materialList as $materialRow){
                        $tmpMaterialId = $materialRow['material_id'];
                        $tmpMaterialRow = \App\Eloquent\Ygt\Product::where(['id'=>$tmpMaterialId])->first();
                        if($tmpMaterialRow){

                            //添加退货信息
                            $tmpMaterialRow['return_purchase_material_id'] = $materialRow['material_id'];
                            $tmpMaterialRow['return_purchase_num'] = $materialRow['num'];
                            $tmpMaterialRow['return_purchase_price'] = $materialRow['price'];

                            if($tmpMaterialRow['return_purchase_num'] == 0){
                                $re = [
                                    'code' => 1,
                                    'message' => '请填写退货数量',
                                ];
                                echo \GuzzleHttp\json_encode($re);die();
                            }
                            if($tmpMaterialRow['return_purchase_price'] == 0){
                                $re = [
                                    'code' => 1,
                                    'message' => '请填写退货单价',
                                ];
                                echo \GuzzleHttp\json_encode($re);die();
                            }


                            if($tmpMaterialRow->seller_company_id){
                                $materialSupplierList[$tmpMaterialRow->seller_company_id][] = $tmpMaterialRow;
                            }else{
                                //材料无供应商时
                                $materialSupplierList['no_supplier'][] = $tmpMaterialRow;
                            }






//                            if($supplierId && $supplierId != $tmpMaterialRow->seller_company_id){
//                                $re = [
//                                    'code' => 1,
//                                    'message' => '请选择相同供应商的材料',
//                                ];
//                                echo \GuzzleHttp\json_encode($re);die();
//                            }
//                            $supplierId = $tmpMaterialRow->seller_company_id;
                        }
                    }
                }else{
                    $re = [
                        'code' => 1,
                        'message' => '请选择需要退货的材料',
                    ];

                    echo \GuzzleHttp\json_encode($re);die();

                }
            }else{
                $re = [
                    'code' => 1,
                    'message' => '请选择需要退货的材料',
                ];

                echo \GuzzleHttp\json_encode($re);die();
            }



            foreach ($materialSupplierList as $supplierId => $supplierMaterialList) {
                if ($supplierId == 'no_supplier') {
                    $supplierId = 0;
                }

                ////生成采购编号
                //获取是当天的第几单
                $dayStartTime = strtotime(date('Ymd'));
                $intradayOrderCount = \App\Eloquent\Ygt\ReturnPurchase::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();

                $ordeTitleIndex = '';
                $intradayOrderCount++;
                if ($intradayOrderCount < 10) {
                    $ordeTitleIndex = sprintf('0%d', $intradayOrderCount);
                } else {
                    $ordeTitleIndex = $intradayOrderCount;
                }
                $purchaseNumber = 'TH' . date('ymd') . $ordeTitleIndex;


                $flow = new \App\Eloquent\Ygt\ReturnPurchase([
                    'uid' => $userId,
                    'company_id' => $companyId,
                    'purchase_number' => $purchaseNumber,
//                'material_id' => $data['material_id'],
                    'supplier_id' => $supplierId,
//                'num' => $data['num'],
                    'content' => $data['content'],
                    'status' => 1,//状态，默认1-待审核
                ]);
                xAssert($flow->save());


                //存入采购申请材料表
                $allMoney = 0;//采购总金额
                if(!empty($supplierMaterialList)){
                    foreach ($supplierMaterialList as $materialRow){
                        $tmpMaterialId = $materialRow['return_purchase_material_id'];
                        $tmpMaterialNum = $materialRow['return_purchase_num'];
                        $tmpMaterialPrice = $materialRow['return_purchase_price'];

                        $allMoney += $tmpMaterialNum*$tmpMaterialPrice;

                        $purchaseMaterialObj = \App\Eloquent\Ygt\ReturnPurchaseMaterial::firstOrNew(['id'=>'']);
                        $purchaseMaterialRow = [
                            'purchase_id' => $flow['id'],
                            'material_id' => $tmpMaterialId,
                            'num' => $tmpMaterialNum,
                            'price' => $tmpMaterialPrice,
                            'company_id' => $companyId,
                        ];
                        $purchaseMaterialObj->fill($purchaseMaterialRow);
                        $purchaseMaterialObj->save();


                        //材料退品表减库存
                        $tmpMaterialRetreatRow = \App\Eloquent\Ygt\MaterialRetreat::where(['material_id'=>$tmpMaterialId])->first();
                        if($tmpMaterialRetreatRow){
                            $tmpMaterialRetreatRow->number = $tmpMaterialRetreatRow->number - $tmpMaterialNum;
                            $tmpMaterialRetreatRow->save();

                            //添加流水
                            $tmpMaterialRetreatId = $tmpMaterialRetreatRow->id;
                            $tmpMaterialRetreatLogObj = \App\Eloquent\Ygt\MaterialRetreatLog::firstOrNew(['id'=>'']);


                            ////生成流水号
                            //获取是当天的第几条
                            $dayStartTime = strtotime(date('Ymd'));
                            $intradayOrderCount = \App\Eloquent\Ygt\MaterialRetreatLog::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();
                            $tmpIndex = '';
                            $intradayOrderCount++;
                            if ($intradayOrderCount < 10) {
                                $tmpIndex = sprintf('0%d', $intradayOrderCount);
                            } else {
                                $tmpIndex = $intradayOrderCount;
                            }
                            $sn = 'CLTPLS' . date('ymd') . $tmpIndex;


                            $tmpInsertRow = [
                                'material_retreat_id' => $tmpMaterialRetreatId,
                                'material_id' => $tmpMaterialId,
                                'number' => $tmpMaterialNum,
                                'user_id' => $userId,
                                'sn' => $sn,
                                'type' => 2,
                                'relate_id' => $flow['id'],
                            ];
                            $tmpMaterialRetreatLogObj->fill($tmpInsertRow);
                            $tmpMaterialRetreatLogObj->save();

                        }

                    }
                }

                $workflowSaveData = [
                    'oa_company_id' => $companyId,
                    'creator_id' => $userId,
                    'related_id' => $flow['id'],
                    'serial_number' => $data['serial_number'],
                    'related_type' => Workflow::RELATE_TYPE_FLOW_RETURN_PURCHASE_APPLICATION,
                    'dispose_code' => 1000,
                    'step' => 1,
                    'assignee_id' => $data['operator_id'],
                    'oa_flow_id' => $data['oa_flow_id'],
                    'oa_flow_config_process_id' => $data['oa_flow_config_process_id']
                ];
                $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);
                $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

                ////发送消息
                //发送消息给下一步审批人
                $messageData           = [
                    'company_id'=> $companyId,
                    'privilege_id'=> '',
                    'form_user_id'=> $userId,
                    'to_user_id'=> $data['operator_id'],
                    'foreign_key'=> $workflow['id'],
                    'type'=>18,
                    'type_id'=> $workflow['id'],
                    'title'=>'退货申请',
                    'content'=>'有新的申请'
                ];
                \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);


                //获取数据
                //退货单号、工厂名、工厂联系电话（可直接拨打）、退品金额
                $purchaseNumber = \App\Engine\Common::changeSnCode($purchaseNumber);
                $allMoney = "¥".sprintf("%.2f",$allMoney);
                $companyName = $companyTel = '';
                $returnPurchaseMoney = 0;
                $companyRow = \App\Eloquent\Ygt\Company::where(['id'=>$companyId])->first();
                if($companyRow){
                    $companyName = $companyRow['title'];
                    $companyTel = $companyRow['mobile'];
                }

                $supplierRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$supplierId])->first();
                if($supplierRow){

                    $messageContent = "退货单号:{$purchaseNumber}rnrn";
                    $messageContent .= "工厂名:{$companyName}rnrn";
                    $messageContent .= "工厂联系电话:{$companyTel}rnrn";
                    $messageContent .= "退品金额:{$allMoney}";

                    $messageData           = [
                        'company_id'=> 2,//供应商企业
                        'privilege_id'=> '',
                        'form_user_id'=> $userId,
                        'to_user_id'=> $supplierRow['user_id'],
                        'foreign_key'=> $workflow['id'],
                        'type'=>35,//纯展示
                        'type_id'=> $workflow['id'],
                        'title'=>'退货申请',
                        'content'=>$messageContent,
                        'theme'=>'退品退货'
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);
                }

                //发送消息给仓库
                $privilegeIdArr     = \App\Eloquent\Ygt\Privilege::getPrivilegeIds( $companyId, 3 );
                foreach($privilegeIdArr as $key=>$val)
                {
                    $messageData        = [
                        'company_id' => $companyId,
                        'privilege_id' => $val,
                        'form_user_id' => $userId,
                        'to_user_id' => 0,
                        'foreign_key' => $workflow['id'],
                        'type' => 35,//纯展示
                        'type_id' => $workflow['id'],
                        'title' => '退货申请',
                        'content' => $messageContent,
                        'type_status' => 1,
                        'theme'=>'退品退货'
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);
                }
            }



        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }

        \DB::commit();
    }

    // 加班费流程
    public function xxxxxxx($userId, $companyId, $data)
    {
        // TODO: 数据库事务
        // TODO: 在加班费表中添加记录
        // TODO: workflow表添加记录

    }


    // 补勤流程
    public function newWorkdayShiftFlow($userId, $companyId, $data)
    {
        try {
            \DB::beginTransaction();
            $data['time'] = is_numeric($data['time']) ? $data['time'] : strtotime($data['time']);
            $flow = new FlowSupplement([
                'time' => $data['time'],
                'reasons' => $data['reasons'],
            ]);
            xAssert($flow->save());

            $workflowSaveData = [
                'oa_company_id' => $companyId,  // 公司ID，造抄
                'creator_id' => $userId,     // 流程创建都ID，造抄
                'related_id' => $flow['id'], // 补勤表的ID，造抄
                'serial_number' => $data['serial_number'],  // 流程编号，造抄
                'related_type' => Workflow::RELATE_TYPE_FLOW_WORKDAY_SHIT, // 流程类型，需要和文档‘获取审批流程列表（分页）’接口中的对应
                'dispose_code' => 1000,    // 创建流程编码，造抄
                'step' => 1,       // 当前流程第几步，造抄
                'assignee_id' => $data['operator_id'],    // 下一步经办人ID，造抄
                'oa_flow_id' => $data['oa_flow_id'],     // 所属哪个流程，造抄
                'oa_flow_config_process_id' => $data['oa_flow_config_process_id']   // 所属哪个流程步骤，造抄
            ];

            // 保存至workflow表，造抄
            $workflow = $this->initWorkflow($workflowSaveData, $data['copy_ids']);

            // 保存图片、附件，造抄
            $this->saveFile($workflow['id'], $flow['id'], 0, $data['image_url'], $data['enclosure_url']);

            /* author:wenwenbin 2018-1-24  添加推送*/
            $assignee = Contacts::with('userInfo')->find($data['operator_id']);
            if ($assignee && $assignee->userInfo) {
                $jPush = new JPushService();
                $jPush->appSend(
                    [
                        $assignee->userInfo->customer_name
                    ],
                    '您有一条新的补勤审批待处理，请及时查看', '补勤审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'wait', 'id' => $workflow['id']]
                    ]
                );
            }
            $copyIds = is_array($data['copy_ids']) ? $data['copy_ids'] : explode(',', $data['copy_ids']);
            if (count($copyIds)) {
                $copyList = Contacts::whereIn('id', $copyIds)->with('userInfo')->get();
                $copyMobile = [];
                foreach ($copyList as $copy) {
                    if ($copy->userInfo) $copyMobile[] = $copy->userInfo->customer_name;
                }
                $jPush = new JPushService();
                $jPush->appSend(
                    $copyMobile, '您收到一条新的补勤审批抄送，请注意查看', '补勤审批',
                    [
                        'type' => 1,
                        'ios_url' => 'OAWaitMyApprovalDetaileController',
                        'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                        'params' => ['from' => 'unread', 'id' => $workflow['id']]
                    ]
                );
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\Throwable $t) {
            \DB::rollBack();
            xThrow(ERR_LOGIC, $t->getMessage());
        }
        \DB::commit();
    }

    /**
     * 流程初始化
     * @author sojo
     * @param $saveData
     * @param string $copyToIds
     * @return \App\Eloquent\Oa\Workflow
     */
    public function initWorkflow($saveData, $copyToIds = '')
    {
        $workflow = (new Workflow())->create($saveData);
        if (!empty($copyToIds)) {
            $copyToIds = is_array($copyToIds) ? $copyToIds : explode(',', $copyToIds);
            (new WorkflowCopy())->add($workflow['id'], $copyToIds);
        }
        (new WorkflowLog())->add($workflow['id'], $workflow['dispose_code'], $saveData['creator_id'], $saveData['assignee_id']);
        return $workflow;
    }

    // 保存文件
    public function saveFile($workflowId, $masterId, $branchId = 0, $imageUrl = '', $enclosureUrl = '')
    {
        $time = time();
        $imageList = empty($imageUrl) ? [] : explode(',', $imageUrl);
        foreach ($imageList as &$file) {
            $tmp = explode('/', $file);
            $tmp = end($tmp);
            $oldName = explode('.', $tmp)[0];
            $file = [
                'oa_workflow_id' => $workflowId,
                'oa_flow_master_id' => $masterId,
                'oa_flow_branch_id' => $branchId,
                'old_name' => $oldName,
                'url' => $file,
                'type' => 1,
                'created_at' => $time,
                'updated_at' => $time,
            ];
        }
        $enclosureList = empty($enclosureUrl) ? [] : explode(',', $enclosureUrl);
        foreach ($enclosureList as &$file) {
            $tmp = explode('/', $file);
            $tmp = end($tmp);
            $oldName = explode('.', $tmp)[0];
            $file = [
                'oa_workflow_id' => $workflowId,
                'oa_flow_master_id' => $masterId,
                'oa_flow_branch_id' => $branchId,
                'old_name' => $oldName,
                'url' => $file,
                'type' => 2,
                'created_at' => $time,
                'updated_at' => $time,
            ];
        }
        $fileList = array_merge($imageList, $enclosureList);
        FlowFile::insert($fileList);
    }

    /**
     * 生成序列号
     * @author LuLingFeng
     * @param $type
     * @param int $time
     * @return string
     */
    public function generateSerialNumber($type, $time = -1)
    {
        if ($time < 0) $time = time();
        return strtoupper($type) . rand(0, 9) . rand(0, 9) . $time . rand(0, 9) . rand(0, 9);
    }

    public static function getFlowAbbr($int)
    {
        $data = [
            self::RELATE_TYPE_ABBR_FLOW_DOCUMENT,
            self::RELATE_TYPE_ABBR_FLOW_LEAVE,
            self::RELATE_TYPE_ABBR_FLOW_SEAL_USE,
            self::RELATE_TYPE_ABBR_FLOW_CAR_USE,
            self::RELATE_TYPE_ABBR_FLOW_RESIGN,
            self::RELATE_TYPE_ABBR_FLOW_TRANSFER_POST,
            self::RELATE_TYPE_ABBR_FLOW_REIMBURSE,
            self::RELATE_TYPE_ABBR_FLOW_EGRESS,
            self::RELATE_TYPE_ABBR_FLOW_BUSINESS_TRIP,
            self::RELATE_TYPE_ABBR_FLOW_HOLIDAY_SHIFT,
            self::RELATE_TYPE_ABBR_FLOW_WORKDAY_SHIT,
            self::RELATE_TYPE_ABBR_FLOW_OVERTIME_PAY,
            self::RELATE_TYPE_ABBR_FLOW_RECEIVE_APPLY_FOR,
            self::RELATE_TYPE_ABBR_FLOW_PROCUREMENT,
            self::RELATE_TYPE_ABBR_FLOW_CONTENT,
            self::RELATE_TYPE_ABBR_FLOW_PETTY_CASH,
            self::RELATE_TYPE_ABBR_FLOW_SYSTEM_SOLUTIONS,
            self::RELATE_TYPE_ABBR_FLOW_RECEUITMENT_NEEDS,
            self::RELATE_TYPE_ABBR_FLOW_REWARD_AND_PUNISH,
            self::RELATE_TYPE_ABBR_FLOW_DIMISSION,
            self::RELATE_TYPE_ABBR_FLOW_BECOME_PROMOTE_SALARY,
            self::RELATE_TYPE_ABBR_FLOW_REPLENISH_SIGN,
            self::RELATE_TYPE_ABBR_FLOW_INTERVIEW,
            self::RELATE_TYPE_ABBR_FLOW_TAKING_WORK,
            self::RELATE_TYPE_ABBR_FLOW_CUSTOMER_ORDER,
            self::RELATE_TYPE_ABBR_FLOW_PURCHASE_APPLICATION,
            self::RELATE_TYPE_ABBR_FLOW_RETURN_PURCHASE_APPLICATION,
        ];
        return $data[$int];
    }

    public static function getFlowType($fullString)
    {
        $int = 0;
        switch ($fullString) {
            case 'document':
                $int = 1;
                break;
            case 'leave':
                $int = 2;
                break;
            case 'seal':
                $int = 3;
                break;
            case 'car':
                $int = 4;
                break;
            case 'dimission':
                $int = 5;
                break;
            case 'position':
                $int = 6;
                break;
            case 'reimburse':
                $int = 7;
                break;
            case 'go_out':
                $int = 8;
                break;
            case 'business_trip':
                $int = 9;
                break;
            case 'days_off':
                $int = 10;
                break;
            case 'supplement':
                $int = 11;
                break;
            case 'overtime_pay':
                $int = 12;
                break;
            case 'receive_apply_for':
                $int = 13;
                break;
            case 'procurement':
                $int = 14;
                break;
            case 'contract':
                $int = 15;
                break;
            case 'petty_cash':
                $int = 16;
                break;
            case 'system_solutions':
                $int = 17;
                break;
            case 'recruitment_needs':
                $int = 18;
                break;
            case 'reward_and_punish':
                $int = 19;
                break;
            case 'dimissions':
                $int = 20;
                break;
            case 'become_promote_salary':
                $int = 21;
                break;
            case 'replenish_sign':
                $int = 22;
                break;
            case 'interview':
                $int = 23;
                break;
            case 'taking_work':
                $int = 24;
                break;
            case 'customer_order':
                $int = 25;
                break;
            case 'purchase_application':
                $int = 26;
                break;
            case 'return_purchase_application':
                $int = 27;
                break;
        }
        $int--;
        return $int;
    }

    public static function getLeaveTypeStr($type)
    {
        $str = '其他';
        switch ($type) {
            case 1:
                $str = '病假';
                break;
            case 2:
                $str = '事假';
                break;
            case 3:
                $str = '产假';
                break;
            case 4:
                $str = '工伤假';
                break;
            case 5:
                $str = '陪产假';
                break;
            case 6:
                $str = '婚假';
                break;
            case 7:
                $str = '丧假';
                break;
            case 8:
                $str = '年休假';
                break;
        }
        return $str;
    }

    public static function getSealFileTypeStr($type)
    {
        $str = '其他';
        switch ($type) {
            case 1:
                $str = '公告类';
                break;
            case 2:
                $str = '规章制度类';
                break;
            case 3:
                $str = '合同类';
                break;
        }
        return $str;
    }

    public static function getSealTypeStr($type)
    {
        $str = '其他';
        switch ($type) {
            case 1:
                $str = '公章';
                break;
            case 2:
                $str = '合同章';
                break;
            case 3:
                $str = '法人章';
                break;
        }
        return $str;
    }

    public static function getTemplate($type)
    {
        $data = [];
        switch ($type) {
            case 'doc':
                break;
            case 'lv':
                // 请假类型
                $data['leave_type'] = [
                    [
                        'type' => 1,
                        'type_str' => '病假',
                    ],
                    [
                        'type' => 2,
                        'type_str' => '事假',
                    ],
                    [
                        'type' => 3,
                        'type_str' => '产假',
                    ],
                    [
                        'type' => 4,
                        'type_str' => '工伤假',
                    ],
                    [
                        'type' => 5,
                        'type_str' => '陪产假',
                    ],
                    [
                        'type' => 6,
                        'type_str' => '其它',
                    ]
                ];
                break;
            case 'su':
                // 文件类型
                $data['file_type'] = [
                    [
                        'type' => 1,
                        'type_str' => '公告类',
                    ],
                    [
                        'type' => 2,
                        'type_str' => '规章制度类',
                    ],
                    [
                        'type' => 3,
                        'type_str' => '合同类',
                    ],
                ];
                // 章类型
                $data['seal_type'] = [
                    [
                        'type' => 1,
                        'type_str' => '公章',
                    ],
                    [
                        'type' => 2,
                        'type_str' => '合同章',
                    ],
                    [
                        'type' => 3,
                        'type_str' => '法人章',
                    ],
                    [
                        'type' => 0,
                        'type_str' => '其他',
                    ],
                ];
                break;
            case 'cu':
                break;
            case 'tp':
                break;
            case 'rb':
                break;
            case 'eg':
                break;
            case 'bt':
                break;
            case 'hs':
                break;
            case 'ws':
                break;
            case 'op':
                break;
            case 'raf':
                break;
            case 'pro':
                break;
            case 'con':
                break;
            case 'pc':
                break;
            case 'ss':
                break;
            case 'rn':
                break;
            case 'rap':
                break;
            case 'dim':
                break;
            case 'bps':
                break;
            default:
                break;
        }
        return $data;
    }
}